package com.erhuogo.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.erhuogo.dao.MemberDao;
import com.erhuogo.entity.CommodityInfo;
import com.erhuogo.entity.Favorite;
import com.erhuogo.entity.Member;
import com.erhuogo.util.PageHibernateCallback;

/**
 * 会员Dao的实现类
 * 
 * @author aibinxiao
 * @date 2016年10月9日 下午4:19:04
 */
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao {
	private static Logger logger = LoggerFactory.getLogger(MemberDaoImpl.class);
	private List<Member> members=null;
	private Member member=null;
	private Favorite favo=null;
	/**
	 * 1.用户登陆Dao实现类
	 */
	@Override
	public Member login(String username, String password) {
		if (StringUtils.isNumeric(username)) {
			// 输入的全是数字，则为手机号登陆
			String hql = "from Member where phoneNumber = ? and password = ? and shieldStatus = ?";
			List<Member> list = this.getHibernateTemplate().find(hql, username, password, 0);
			if (list != null && list.size() > 0) {
				logger.info("用户手机号登陆" + list.get(0));
				return list.get(0);
			}
		} else {
			// 输入的全不是数字，则为用户名登陆
			String hql = "from Member where nickName = ? and password = ? and shieldStatus = ?";
			List<Member> list = this.getHibernateTemplate().find(hql, username, password, 0);
			if (list != null && list.size() > 0) {
				logger.info("用户名登陆" + list.get(0));
				return list.get(0);
			}
		}
		return null;
	}

	/**
	 * 2.验证手机号是否已经注册Dao实现类
	 */
	@Override
	public boolean findByPhoneNumber(String phoneNumber) {
		boolean flag = false;
		String hql = "from Member where phoneNumber = ?";
		List<Member> list = this.getHibernateTemplate().find(hql, phoneNumber);
		if (list != null && list.size() > 0) {
			flag = true;
			logger.info("手机号" + phoneNumber + "已经注册过了！");
		}
		return flag;
	}

	/**
	 * 3.用户注册Dao实现类
	 */
	@Override
	public boolean addMember(Member member) {
		boolean flag = true;
		try {
			this.getHibernateTemplate().save(member);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 4.计算多少符合条件记录条数Dao实现类
	 */
	@Override
	public int countByParams(String id, String nickName, String startDate, String endDate) {
		int count = 0;
		// 使用离线条件查询.
		DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
		if(!StringUtils.isEmpty(id)){
			Integer memId = Integer.valueOf(id);
			criteria.add(Restrictions.idEq(memId));
		}
		if(!StringUtils.isEmpty(nickName)){
			criteria.add(Restrictions.like("nickName", nickName, MatchMode.ANYWHERE));
		}
		if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			criteria.add(Restrictions.between("regTime", startDate, endDate));
		}
		// 倒序排序输出:
		criteria.addOrder(Order.asc("id"));
		// 执行查询:
		List<Member> list = this.getHibernateTemplate().findByCriteria(criteria);
		if (list != null && list.size() > 0) {
			count = list.size();
			logger.info("找到("+ list.size() +")个符合查询条件的用户");
		} else{
			logger.info("没有找到符合查询条件求的用户");
		}
		return count;
	}

	/**
	 * 5.查询出指定开始索引和条数的记录集合Dao实现类
	 */
	@Override
	public List<Member> findPageByParams(String id, String nickName, String startDate, String endDate, int startIndex,
			int records) {
		List<Member> result = null;
		// 使用离线条件查询.
		DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
		if(!StringUtils.isEmpty(id)){
			Integer memId = Integer.valueOf(id);
			criteria.add(Restrictions.idEq(memId));
		}
		if(!StringUtils.isEmpty(nickName)){
			criteria.add(Restrictions.like("nickName", nickName, MatchMode.ANYWHERE));
		}
		if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			criteria.add(Restrictions.between("regTime", startDate, endDate));
		}
		// 升序排序输出:
		criteria.addOrder(Order.asc("id"));
		// 执行查询:
		List<Member> list = this.getHibernateTemplate().findByCriteria(criteria, startIndex, records);
		if (list != null && list.size() > 0) {
			result = list;
			logger.info("找到("+ list.size() +")个符合查询条件的用户");
		} else{
			logger.info("没有找到符合查询条件求的用户");
		}
		return result;
	}
	
	/**
	 * 6.根据ID更新用户状态Dao实现类
	 */
	@Override
	public void updateStatus(Integer memId, Integer status) throws Exception {
		String hql = "from Member where id = ?";
		List<Member> list = this.getHibernateTemplate().find(hql, memId);
		if(list!=null && list.size()>0){
			Member member = list.get(0);
			member.setShieldStatus(status);
			this.getHibernateTemplate().saveOrUpdate(member);
		}
	}

	@Override
	public Member getMemberById(String id) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,Integer.parseInt(id));
		if(members.size()>0){
			member=members.get(0);
		}
		return member;
	}

	@Override
	public boolean checkPassword(Member mem) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,mem.getId());
		if(members.size()>0){
			member=members.get(0);
		}
		if(member.getPassword().equals(mem.getPassword())){
			return true;
		}else{
			return false;
		}	
	}

	@Override
	public boolean alterPws(String memId, String newPws) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,Integer.parseInt(memId));
		if(members.size()>0){
			member=members.get(0);
			member.setPassword(newPws);
			this.getHibernateTemplate().saveOrUpdate(member);
			return true;
		}
		return false;
	}

	@Override
	public boolean uploadPic(int memId, String path) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,memId);
		if(members.size()>0){
			member=members.get(0);
			member.setPortrait(path);
			this.getHibernateTemplate().saveOrUpdate(member);
			return true;
		}
		return false;
	}

	@Override
	public List<Favorite> getCollections(int memId,int offset, int size) {
		String hql="from Favorite where accountId=? order by id desc";
		List<Favorite> favorites=this.getHibernateTemplate().execute(new PageHibernateCallback<Favorite>(hql, new Object[]{memId}, offset, size));
		return favorites;
	}

	@Override
	public int getCollectionsNum(int memId) {
		int count = 0;
		String hql = "select count(*) from Favorite where accountId=?";
		List<Long> list = this.getHibernateTemplate().find(hql,memId);
		if (list != null && list.size() > 0) {
			count = list.get(0).intValue();
			logger.info("收藏商品数："+count);
		}
		return count;
	}

	@Override
	public boolean deleteCollect(int fId) {
		String hql="from Favorite where id=?";
		List<Favorite> favorites=this.getHibernateTemplate().find(hql, fId);
		if(favorites.size()>0){
			favo=favorites.get(0);
			this.getHibernateTemplate().delete(favo);
			return true;
		}
			
		return false;
	}

}
